﻿using System.Collections;

using Exif.Exceptions;
using Exif.Interfaces;
using Exif.Jpeg.Base;
using Exif.Jpeg.Enums;
using Exif.Tiff;
using System.ComponentModel;

namespace Exif.Jpeg.Segments
{
	///<summary>
	///Application-specific
	///</summary>
	public class SegmentAPPn : JpegSegmentBase
	{
		#region Частные поля класса

		private readonly int _number;

		#endregion

		#region Конструктор

		internal SegmentAPPn(IImageProvider parent, JpegMarker marker, int offset, int length, int number)
			: base(parent, marker, offset, length)
		{
			this._number = number;
		}

		#endregion

		#region Статик методы класса

		public static SegmentAPPn CreateAPPnBlock(IImageProvider parent, JpegMarker marker, int offset,
			int length, int number)
		{
			switch (number)
			{
				case 1:
					return new SegmentAPP1(parent, marker, offset, length);
				case 2:
					return new SegmentAPP2(parent, marker, offset, length);
				default:
					return new SegmentAPPn(parent, marker, offset, length, number);
			}
		}

		#endregion

		#region Свойства класса

		public int Number
		{
			get { return this._number; }
		}

		#endregion
	}


	internal class SegmentAPP1 : SegmentAPPn
	{
		#region Конструктор

		internal SegmentAPP1(IImageProvider parent, JpegMarker marker, int offset, int length)
			: base(parent, marker, offset, length, 1)
		{
			var bytes = parent.ImageReader.ReadBytes(5); // 45 78 69 66 00 - Exif\0
			if (bytes[0] != 0x45 || bytes[1] != 0x78 || bytes[2] != 0x69 || bytes[3] != 0x66 || bytes[4] != 0x00)
			{
				var advanced = 5;
				var rest = parent.ImageReader.ReadBytes(length - advanced - 2); //2 - считанная длинна блока
				advanced = length - 2;

				var dump = new byte[length + 2];
				bytes.CopyTo(dump, 0);
				rest.CopyTo(dump, bytes.Length);

				parent.ImageReader.Advance(advanced * -1);

				throw new BinaryDataException("Неизвестный науке блок APP1", dump);
			}

			parent.ImageReader.ReadByte(); // 00

			TiffInfo = new TiffInfo();
			TiffInfo.Read(parent);
		}

		#endregion

		#region Свойства

		public TiffInfo TiffInfo { get; private set; }

		#endregion
	}

	internal class SegmentAPP2 : SegmentAPPn
	{
		#region Конструктор

		internal SegmentAPP2(IImageProvider parent, JpegMarker marker, int offset, int length)
			: base(parent, marker, offset, length, 2)
		{
		}

		#endregion
	}
}